<template>
  <div class="app-container">

    <el-breadcrumb>
      <el-breadcrumb-item :to="{path:'/index'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>内容管理</el-breadcrumb-item>
      <el-breadcrumb-item>文章类别</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <el-form :inline="true" ref="queryForm" :model="query">
      <el-form-item label="类别名称" prop="name">
        <el-input v-model="query.name" placeholder="请输入类别名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">搜索</el-button>
        <el-button size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="margin-bottom:8px">
      <el-col :span="1.5">
        <el-button type="primary" size="small" plain @click="showDialog(undefined)">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" size="small" plain :disabled="selectedIds.length!==1">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" size="small" plain :disabled="!selectedIds.length">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" size="small" plain disabled>导出</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableData" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50"/>
      <el-table-column prop="id" label="#"/>
      <el-table-column prop="name" label="类别名称"/>
      <el-table-column prop="keywords" label="关键词"/>
      <el-table-column prop="sort" label="排序序号"/>
      <el-table-column prop="enable" label="是否启用">
        <template #default="scope">
          <el-switch v-model="scope.row.enable"
                     :active-value="1"
                     :inactive-value="0"
                     @change="handleEnable(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column prop="isDisplay" label="是否在导航栏显示" width="160px">
        <template #default="scope">
          <el-switch v-model="scope.row.isDisplay"
                     :active-value="1"
                     :inactive-value="0"
                     @change="handleDisplay(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="scope">
          <el-button type="primary" size="mini" @click="showDialog(scope.row)">修改</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <el-pagination
        background
        :page-size="query.pageSize"
        :total="total"
        :current-page.sync="query.currentPage"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"/>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" @closed="handleClose" append-to-body>
      <el-form :model="form" :rules="rules" ref="saveOrUpdateForm" label-width="140px">
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="form.name" placeholder="类别名称"/>
        </el-form-item>
        <el-form-item label="关键词列表" prop="keywords">
          <el-input v-model="form.keywords" placeholder="各关键词使用英文的逗号分隔"/>
        </el-form-item>
        <el-form-item label="是否启用" prop="enable">
          <el-switch v-model="form.enable" :active-value="1" :inactive-value="0"/>
        </el-form-item>
        <el-form-item label="是否在导航栏显示" prop="isDisplay">
          <el-switch v-model="form.isDisplay" :active-value="1" :inactive-value="0"/>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="form.sort" type="number" placeholder="排序序号，0-255之间的整数"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import request from "@/http/request";
import qs from "qs";

export default {
  data() {
    return {
      // 查询参数
      query: {
        currentPage: 1,
        pageSize: 5,
        name: undefined
      },
      // 总记录数
      total: 1,
      // 表格数据
      tableData: [{
        id: 1,
        name: '新闻',
        keywords: '关键词1,关键词2',
        enable: 1,
        isDisplay: 1,
        sort: 1
      }],
      // 选择的ids
      selectedIds: [],
      // 对话框标题
      dialogTitle: '',
      // 对话框显示状态
      dialogVisible: false,
      // 表单对象
      form: {},
      // 验证规则
      rules: {
        name: [
          {required: true, message: '类别名称不能为空', trigger: 'blur'},
          {min: 1, max: 32, message: '类别名称必须是1-32个字符组成', trigger: 'blur'}
        ],
        sort: [{required: true, message: '排序序号不能为空', trigger: 'blur'}]
      }
    };
  },
  methods: {
    listData() {
      /*request({
        url: '/api/content/category/list',
        method: 'get',
        params: this.query
      }).then(res => {
        this.total = res.data.total;
        this.tableData = res.data.list;
      });*/
    },
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
      console.log(this.selectedIds)
    },
    handleQuery() {
      this.query.currentPage = 1
      this.listData()
    },
    resetQuery() {
      this.$refs['queryForm'].resetFields()
      this.handleQuery()
    },
    handleCurrentChange(val) {
      this.query.currentPage = val
      this.listData()
    },
    handleSizeChange(val) {
      this.query.pageSize = val
      this.listData()
    },
    handleDelete(row) {
      request({
        url: `/api/content/category/${row.id}/delete`,
        method: 'post'
      }).then(res => {
        this.$message.success('删除成功')
        this.listData()
      })
    },
    handleEnable(row) {
      if (row.enable === 0) {
        // 启用操作
        request({
          url: `/api/content/category/${row.id}/enable`,
          method: 'post'
        }).then(res => {
          row.enable = 1;
          this.$message.success('启用成功')
        })
      } else {
        // 禁用操作
        request({
          url: `/api/content/category/${row.id}/disable`,
          method: 'post'
        }).then(res => {
          row.enable = 0;
          this.$message.success('禁用成功')
        })
      }
    },
    handleDisplay(val) {
      this.$message.info('handleDisplay!' + val)
      // TODO 修改是否在导航栏显示状态 ...
    },
    showDialog(row) {
      if (row) {
        this.dialogTitle = '修改类别'
        // TODO 查询要修改的数据回显 ...
        /*request({
          url: `/api/content/category/${row.id}`,
          method: 'get'
        }).then(res => {
          this.form = res.data
        });*/
        // 模拟服务端响的应数据
        this.form = JSON.parse(JSON.stringify(row))
        this.dialogVisible = true
      } else {
        this.dialogTitle = '新增类别'
        this.dialogVisible = true
      }
    },
    saveOrUpdate() {
      this.$refs['saveOrUpdateForm'].validate(valid => {
        if (!valid) {
          this.$message.error('请正确填写参数')
          return false
        }
        console.log(this.form);
        if (this.form.id) {
          // 修改操作
          request({
            url: '/api/content/category/update',
            method: 'post',
            data: qs.stringify(this.form)
          }).then(res => {
            this.$message.success('修改成功');
            this.dialogVisible = false
            this.listData()
          })
        } else {
          // 新增操作
          request({
            url: '/api/content/category/addnew',
            method: 'post',
            data: qs.stringify(this.form)
          }).then(res => {
            this.$message.success('新增成功')
            this.dialogVisible = false
            this.listData()
          })
        }
      })
    },
    handleClose() {
      this.form = {
        id: undefined,
        name: undefined,
        keywords: undefined,
        enable: 0,
        isDisplay: 0,
        sort: undefined
      }
      this.$refs['saveOrUpdateForm'].resetFields()
      this.dialogVisible = false
    }
  },
  mounted() {
    this.listData()
  }
}
</script>